<?php
namespace app\index\controller;

use app\common\controller\Base as BaseController;
use app\index\model\Wechat;
use app\common\model\User;
use app\common\model\Activity;

use think\Session;

class Base extends BaseController
{
    public $OauthAccessToken;
    public $user;
    public $activity;

    public function __construct()
    {
        $this->OauthAccessToken = Session::get('OauthAccessToken');
        parent::__construct();
        $this->checkLogin();

        $activityId = (int)$this->request->param('activity_id');
        if($activityId) {
            $this->activity = Activity::get($activityId);
        } else {
            $map['start_time'] = ['lt', time()];
            $map['status'] = 1;
            $this->activity = Activity::where($map)->order('sort asc')->find();
        }
        $this->assign('activity', $this->activity);
        $this->assign('user', $this->user);
        $this->assign('account', $this->user->account);
    }

    /**
     * 授权登录
     */

    public function checkLogin()
    {
        $wechatConfig = config('wechat');
        $options = array(
            'token' => $wechatConfig['wechat_token'],             //填写你设定的key
            'encodingaeskey' => $wechatConfig['wechat_encodingaeskey'],   //填写加密用的EncodingAESKey，如接口为明文模式可忽略
            'appid' => $wechatConfig['wechat_appid'],            //填写高级调用功能的app id
            'appsecret' => $wechatConfig['wechat_appsecret']            //填写高级调用功能的密钥
        );
        $wechat = new Wechat($options);

//        $this->OauthAccessToken = [
//            'access_token' => 'OezXcEiiBSKSxW0eoylIeCri7p8gabYz_xZhmWOW-verdthh-jJvb2Pur_3zGrDMjRvuamvDUXpfdTxjyXtW3_LO9Us3gh6mlhKH45XnvcwQu8yd1vt1w71K6nlzfe7VY5HYRW6H4_XxVREtm-dWDg',
//            'expires_in' => 7200,
//            'refresh_token' => 'OezXcEiiBSKSxW0eoylIeCri7p8gabYz_xZhmWOW-verdthh-jJvb2Pur_3zGrDM3DKTDjen9gvREe15hNswhMfheXd-emJsiGM-apIoAUSWvBF8CXAWJFjglGmMIKTXbo0t9uVpKllUwBWKDKqnDg',
//            'scope' => 'snsapi_userinfo',
//            'openid' => 'oXQE_xFShZq2Mg6lzjS-FePRMp4Y',
//        ];

        if (!$this->OauthAccessToken) {
            //尝试获取token。若获取失败，则表示用户通过的是非Oauth 2.0入口进入应用
            if (!$this->OauthAccessToken = $wechat->getOauthAccessToken()) {
                return $this->redirect($wechat->getOauthRedirect($this->_get_url(), '1', 'snsapi_userinfo'));
            }

        } else {
            // 存在 则验证是否过期
            $isexpires = $wechat->getOauthAuth($this->OauthAccessToken['access_token'], $this->OauthAccessToken['openid']);            //验证access_token是否过期

            // 过期则刷新
            if (!$isexpires) {
                $this->OauthAccessToken = $wechat->getOauthRefreshToken($this->OauthAccessToken['refresh_token']);
            }
        }

        Session::set('OauthAccessToken', $this->OauthAccessToken);

        $this->wechatUserInit($wechat);
    }

    // 信息初始化
    private function wechatUserInit($wechat)
    {
        // 获取用户信息
        $weUser = User::getByOpenid($this->OauthAccessToken['openid']);

        // 不存在，则注册
        if (!$weUser) {
            // 不存在就重新注册
            $weInfo = $wechat->getOauthUserinfo($this->OauthAccessToken['access_token'], $this->OauthAccessToken['openid']);
            $weUser = User::addWechatUser($weInfo);
        }
        $this->user = $weUser;
    }

    /**
     * 获取当前页面完整URL地址
     */
    private function _get_url()
    {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    }
}
